import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getToken } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

// 白名单
const whiteList = ['/login', '/404'] // no redirect whitelist

router.beforeEach(async (to, from, next) => {
  // 开启进度条
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  // determine whether the user has logged in
  const hasToken = getToken()
  // 判断是否有token
  if (hasToken) {
    if (to.path === '/login') {
      // 如果访问的是登录页,就跳转到首页
      next({ path: '/' })
      NProgress.done()
    } else {
      // 判断当前vuex中有没有用户数据,有就不用重新发请求
      if (!store.state.user.userInfo.userId) {
        const { roles } = await store.dispatch('user/getUserInfoAsync')
        // console.log(roles, '进行权限处理')
        const otherRoutes = await store.dispatch('permission/filterRoutes', roles.menus)

        // 拿到权限信息之后, 应该根据权限信息, 从动态路由模块中筛选出, 需要追加的路由,
        // 追加到routes规则中, addRoutes
        router.addRoutes([...otherRoutes, { path: '*', redirect: '/404', hidden: true }])
        next({
          ...to, // next({ ...to })的目的,是保证路由添加完了再进入页面 (可以理解为重进一次)
          replace: true, // 重进一次, 不保留重复历史
        })
        return
      }
      next()
    }
  } else {
    /* has no token*/
    // 没有token,判断是否是白名单,是的话就通行,不是的话就跳转到登录页面
    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
